﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Stub.GoogleJwt
{
    public class PostBackPurchaseHandler : IHttpHandler
    {
        HttpResponse Response;
        HttpRequest Request;
        HttpServerUtility Server;

        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        public void ProcessRequest(HttpContext context)
        {
            Response = context.Response;
            Request = context.Request;
            Server = context.Server;

            try
            {
                Main();
            }
            catch (Exception unhandled)
            {
                Response.Clear();
                Response.ContentType = "text/html";
                Response.Write("<http><head><title>Problem with request</title></head><body>");
                Response.Write(unhandled.Message);
                Response.Write("</body></http>");
            }
        }

        private void Main()
        {

            StreamReader reader = new StreamReader(Request.InputStream);
            string input = reader.ReadToEnd();

            using (StreamWriter fout = new StreamWriter(Path.Combine(Server.MapPath("/ac"), "purchase.json")))
            {
                fout.Write(input);
            }

            if(!input.StartsWith("jwt="))
                throw new Exception("Invalid Input, expecting jwt=");

            Stub.Jwt.JsonWebToken jwt = new Jwt.JsonWebToken(input.Substring(4));

            if (!jwt.Valid("RxMr0dZSP9WAfKC5vJ_n3w"))
                throw new Exception("Invalid Jwt");
            JObject jobj = JObject.Parse(jwt.PayLoad);
            Response.Clear();
            Response.ContentType = "text";
            Response.StatusCode = 200;
            Response.Write(((string)jobj["response"]["orderId"]).Trim());
            Response.Flush();
        }

        #endregion
    }
}
